﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace 智慧无纸化会议客户端软件.Code
{
    public class RequestService
    {
        static readonly string _AppId = "b58c579f-7288-3169-a259-5a5c03765629";
        static readonly string _AppToken = "4GHORJQRNRhL7I7XYZnctDfwoEGDAYUNyknzU4fBv7z49FgWHIB1yg==";

        public static string Token { get; set; }

        public static long? TimeDiff { get; set; }

        public static string ServeiceUrl { get; set; }

        public static Dictionary<string, object> GetRequest(string url, Dictionary<string, string> headers, int timeout, bool isLog = false)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            url = ServeiceUrl + "/api/" + url;
            var response = Request(url, null, HttpMethod.Get, headers, timeout);
            dict["Url"] = url;
            if (headers != null) dict["Headers"] = Common.ToJson(headers);
            dict["ResponseContent"] = response;
            return getResponse(isLog, dict, response);
        }

        static Dictionary<string, object> getResponse(bool isLog, Dictionary<string, string> dict, string response)
        {
            var res = Common.JsonToDictionary(response);
            if (res.ContainsKey("Token")) Token = res.GetStringValue("Token");

            var msg = res.GetStringValue("Message");
            if (res.ContainsKey("Ack"))
            {
                msg = res.GetValue<Dictionary<string, object>>("Ack").GetStringValue("Message");
            }
            if (!string.IsNullOrEmpty(msg))
            {
                LoggerProxy.WriteLog("Message", "RequestService", "Request", dict);
                throw new Exception(msg);
            }
            else if (isLog) LoggerProxy.Info("RequestService", "Request", dict);
            return res;
        }

        static string Request(string url, HttpContent content, HttpMethod method, Dictionary<string, string> headers, int timeout = 0)
        {
            url = Common.AddUrlRandom(url);

            HttpClient client = new HttpClient();
            if (timeout > 0) client.Timeout = new TimeSpan(0, timeout, 0);

            HttpRequestMessage request = new HttpRequestMessage(method, url);

            if (content != null) request.Content = content;
            if (headers != null) foreach (var h in headers) request.Headers.Add(h.Key, h.Value);

            Task<HttpResponseMessage> response = client.SendAsync(request);

            return response.Result.Content.ReadAsStringAsync().Result;
        }

        static Dictionary<string, string> getHeaders()
        {
            Dictionary<string, string> headers = new Dictionary<string, string>();
            var token = string.IsNullOrEmpty(Token) ? _AppToken : Token;
            headers.Add("Token", token);
            headers.Add("Access-Token", getAccessToken(token));
            return headers;
        }

        static string getAccessToken(string token)
        {
            long time = Common.GetDateTotalMilliseconds(DateTime.Now);
            if (TimeDiff != null) time += TimeDiff.Value;
            var md5str = Common.ComputeStringMd5(_AppId + time + token);
            return Common.ToBase64String(_AppId + '@' + time + "@" + md5str);
        }

        public static long GetCurrentTime(string serviceUrl)
        {
            try
            {
                if (!serviceUrl.ToLower().StartsWith("http://")) serviceUrl = "http://" + serviceUrl;
                ServeiceUrl = serviceUrl.TrimEnd('/');
                string url = "Default/GetCurrentTime";
                var res = GetRequest(url, new Dictionary<string, string>(), 1000);
                long time = res.GetValue<long>("Time");
                TimeDiff = time - Common.GetDateTotalMilliseconds(DateTime.Now);
                return time;
            }
            catch
            {
                ServeiceUrl = string.Empty;
                return 0;
            }
        }

        public static List<ClientPublish> GetClientPublish(DateTime dateTime)
        {
            string url = "VisitUser2/GetClientPublish?CreateDate=" + Common.GetDateTotalMilliseconds(dateTime);

            var res = GetRequest(url, getHeaders(),0, false);
            if (res.ContainsKey("Data")) return Common.DictionaryListToList<ClientPublish>(res.GetValue<List<Dictionary<string, object>>>("Data"));
            else return null;
        }
    }
}
